import 'package:countdown/common/services/IsarDatabase.dart';
import 'package:countdown/page/event/widget/emoji_picker.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../common/model/model.dart';
import '../list/index.dart';
import 'index.dart';

class EventController extends GetxController {
  var state = EventState();

  EventController();

  final ListController listController = Get.find();

  final isar = IsarDatabaseService.to.isar();

  //save
  Future<void> save() async {
    final eventRecords = EventRecord()
      ..type = state.buttonPanelConfig.value
      ..title = state.title
      ..emoji = state.buttonPanelConfig.emoji
      ..date = state.date
      ..cardTitle = state.cardTitle
      ..cardSubTitle = state.cardSubTitle
      //毫秒
      ..sort = DateTime.now().millisecondsSinceEpoch
      ..ifTop = false
      ..lunar = state.lunar
      ..ifArchive = false;

    await isar.writeTxn(() async {
      await isar.eventRecords.put(eventRecords);
    });
    listController.onRefresh();
    //保存完成清空表单
    empty();
  }

  //save
  Future<void> updateEvent() async {
    final eventRecords = EventRecord()
      ..id = state.eventRecords.id
      ..type = state.buttonPanelConfig.value
      ..title = state.title
      ..emoji = state.buttonPanelConfig.emoji
      ..date = state.date
      ..cardTitle = state.cardTitle
      ..cardSubTitle = state.cardSubTitle
      //毫秒
      ..sort = DateTime.now().millisecondsSinceEpoch
      ..ifTop = false
      ..lunar = state.lunar
      ..ifArchive = false;

    await isar.writeTxn(() async {
      int id = await isar.eventRecords.put(eventRecords);
      print(id);
    });
    listController.onRefresh();
    //保存完成清空表单
    empty();
  }

  //清空
  void empty() {
    state = EventState();
  }

  void openKeyWord(BuildContext context) {
    showEmojiPicker(context, true, onTap: (o) {
      state.emojiTemp = o.name;
      Navigator.pop(context);
    });
  }
}
